package cn.anlucky.apiadmin.service.impl;

import cn.anlucky.apiadmin.pojo.CustomException;
import cn.anlucky.apiadmin.utils.RedisUtil;
import cn.anlucky.apiadmin.vo.R;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.anlucky.apiadmin.pojo.Webinfo;
import cn.anlucky.apiadmin.service.WebinfoService;
import cn.anlucky.apiadmin.mapper.WebinfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
* @author 95135
* @description 针对表【webinfo】的数据库操作Service实现
* @createDate 2024-04-16 14:57:05
*/
@Service
@Slf4j
public class WebinfoServiceImpl extends ServiceImpl<WebinfoMapper, Webinfo>
    implements WebinfoService{

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 取网页全局信息
     *
     * @return
     */
    @Override
    public R getWebInfo() {
        Object webinfo = redisUtil.get("webinfo");

        if (Objects.nonNull(webinfo)){
            log.info("使用缓存");
            return R.success("成功",webinfo);
        }

        List<Webinfo> webinfos = baseMapper.selectList(null);
        if (webinfos.size() > 0){
            log.info("不使用缓存");
            webinfo = webinfos.get(0);
            redisUtil.set("webinfo",webinfo,3600);
            return R.success("成功",webinfo);
        }
       throw new CustomException("查询失败，未找到信息！");
    }

    /**
     * 更新网站信息
     *
     * @param webinfo
     * @return
     */
    @Override
    public R updateWebInfoById(Webinfo webinfo) {

        if (Objects.isNull(webinfo)){
            throw new CustomException("更新信息为空，未接收到参数");
        }

        if (Objects.isNull(webinfo.getId())){
            throw new CustomException("主键ID不允许为空");
        }

        LambdaUpdateWrapper<Webinfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Webinfo::getTitle,webinfo.getTitle())
                .set(Webinfo::getAuthor,webinfo.getAuthor())
                .set(Webinfo::getDescription,webinfo.getDescription())
                .set(Webinfo::getIcpinfo,webinfo.getIcpinfo())
                .set(Webinfo::getKeywords,webinfo.getKeywords())
                .eq(Webinfo::getId,webinfo.getId());

        int update = baseMapper.update(null, updateWrapper);
        if (update>0){
            redisUtil.del("webinfo");
        }
        return R.success("更新成功");
    }
}




